package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.SQLOutput;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public  class ReportController {


    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;


    @RequestMapping("/getMemberReport")
    private Result getMemberReport() {

        Map<String, Object> map = new HashMap<>();
        List<String> months = new ArrayList<>();

        Calendar calendar = Calendar.getInstance();

        calendar.add(Calendar.MONTH, -12);

        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            Date date = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy.MM").format(date));
        }

        map.put("months", months);

        List<Integer> memberCount = memberService.findMemberCountByMonths(months);

        map.put("memberCount", memberCount);

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }


    @RequestMapping("/getSetmealReport")
    private Result getSetmealReport() {


        List<Map<String, Object>> list = setmealService.findSetmealCount();

        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, list);
    }


    @RequestMapping("/getBusinessReportData")
    private Result getBusinessReportData() {
        try {
            Map<String, Object> data = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }

    }

    @RequestMapping("/exportBusinessReport")
    private Result exportBusinessReport(HttpSession session, HttpServletResponse response) {
        try {
            Map<String, Object> data = reportService.getBusinessReportData();

            String reportDate = (String) data.get("reportDate");
            Integer todayNewMember = (Integer) data.get("todayNewMember");
            Integer totalMember = (Integer) data.get("totalMember");
            Integer thisWeekNewMember = (Integer) data.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) data.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) data.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) data.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) data.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) data.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) data.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) data.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) data.get("hotSetmeal");


            InputStream is = session.getServletContext().getResourceAsStream("/template" + File.separator + "report_template.xlsx");

            XSSFWorkbook workbook = new XSSFWorkbook(is);

            XSSFSheet sheet = workbook.getSheetAt(0);

            sheet.getRow(2).getCell(5).setCellValue(reportDate);//设置日期

            sheet.getRow(4).getCell(5).setCellValue(todayNewMember);//设置今日新增会员
            sheet.getRow(4).getCell(7).setCellValue(totalMember);//总会员数量
            sheet.getRow(5).getCell(5).setCellValue(thisWeekNewMember);//本周新增会员
            sheet.getRow(5).getCell(7).setCellValue(thisMonthNewMember);//本月新增会员

            sheet.getRow(7).getCell(5).setCellValue(todayOrderNumber);//今日预约数
            sheet.getRow(7).getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            sheet.getRow(8).getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            sheet.getRow(8).getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            sheet.getRow(9).getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            sheet.getRow(9).getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            for (Map map : hotSetmeal) {
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");

                sheet.getRow(rowNum).getCell(4).setCellValue(name);
                sheet.getRow(rowNum).getCell(5).setCellValue(setmeal_count);
                sheet.getRow(rowNum).getCell(6).setCellValue(proportion.doubleValue());
                sheet.getRow(rowNum).getCell(7).setCellValue("无");
                rowNum++;
            }

            OutputStream out = response.getOutputStream();

            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");

            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);

        }

    }


    @RequestMapping("/exportBusinessReport4PDF")
    private Result exportBusinessReport4PDF(HttpSession session, HttpServletResponse response) {
        try {
            Map<String, Object> data = reportService.getBusinessReportData();

            List<Map> hotSetmeal = (List<Map>) data.get("hotSetmeal");

            //二进制模版所在位置
            String jasperPath = session.getServletContext().getRealPath("template")+File.separator+"health_business.jasper";

            //填充数据
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, data, new JRBeanCollectionDataSource(hotSetmeal));

            //构建输出流
            OutputStream out = response.getOutputStream();

            //设置文件下载的头
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");

            //流对流输出到浏览器
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);
            out.flush();
            out.close();


            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);

        }

    }


}
